package com.zyx.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.*;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import java.io.IOException;

@Configuration
@PropertySource("db.properties")
@ComponentScan("com.zyx.mapper")
@MapperScan("com.zyx.mapper")
public class MybatisConfig {
    @Value("${db.driver:com.mysql.cj.jdbc.Driver}")
    private String diver;
    @Value("${db.url:jdbc:mysql:/db}")
    private String url;
    @Value("${db.username:root}")
    private String username;
    @Value("${db.password}")
    private String password;

    @Bean(name = "ds",initMethod = "init",destroyMethod = "close")
    @Primary
    public DruidDataSource ds(){
        DruidDataSource ds  = new DruidDataSource();
        ds.setDriverClassName(diver);
        ds.setUsername(username);
        ds.setUrl(url);
        ds.setPassword(password);
        return ds;
    }

    @Bean(name = "sf")
    @Primary
    public SqlSessionFactoryBean sf(DruidDataSource ds) throws IOException {
        SqlSessionFactoryBean sf = new SqlSessionFactoryBean();
        sf.setDataSource(ds);

        //resources/XXXmapper.xml
        sf.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath*:mapper/*Mapper*.xml"));
        return sf;
    }

}
